package com.example.deliveryapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class SignInActivity extends AppCompatActivity {
    private EditText phoneEditText, passwordEditText;
    private Button signInButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_in);

        // 初始化 UI 组件
        phoneEditText = findViewById(R.id.phone_on_sign_in);
        passwordEditText = findViewById(R.id.password_on_sign_in);
        signInButton = findViewById(R.id.button_sign_in_on_sign_in_page);

        // 为登录按钮设置点击事件监听器
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    // 获取用户输入的数据
                    String phone = phoneEditText.getText().toString().trim();
                    String password = passwordEditText.getText().toString().trim();

                    // 创建 JSON 请求体
                    JSONObject jsonBody = new JSONObject();
                    jsonBody.put("phone", phone);
                    jsonBody.put("password", password);

                    // 创建请求体
                    RequestBody requestBody = RequestBody.create(
                            MediaType.parse("application/json; charset=utf-8"),
                            jsonBody.toString()
                    );

                    // 创建 OkHttpClient 实例
                    OkHttpClient client = new OkHttpClient();

                    // 构建请求
                    Request request = new Request.Builder()
                            .url("http://107.172.88.177:86/v1/login")  // 替换为实际的登录接口 URL
                            .post(requestBody)
                            .addHeader("Content-Type", "application/json; charset=utf-8") // 添加请求头
                            .build();

                    // 发送异步请求
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            runOnUiThread(() -> {
                                Toast.makeText(SignInActivity.this, "登录失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                            });
                        }


                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                final String responseData = response.body().string();
                                runOnUiThread(() -> {
                                    Toast.makeText(SignInActivity.this, "登录成功: " + responseData, Toast.LENGTH_LONG).show();

                                    // 使用 SharedPreferences 保存手机号
                                    SharedPreferences sharedPreferences = getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    editor.putString("userPhone", phone); // 确保这里的 userPhone 是从输入框获取的手机号
                                    editor.putBoolean("isLoggedIn", true);
                                    editor.apply();

                                    //登录成功后，跳转至地址页
                                    Intent intent = new Intent(SignInActivity.this,MainPageActivity.class);
                                    startActivity(intent);

                                });
                            } else {
                                runOnUiThread(() -> {
                                    Toast.makeText(SignInActivity.this, "登录失败，状态码：" + response.code(), Toast.LENGTH_LONG).show();
                                });
                            }
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                    runOnUiThread(() -> {
                        Toast.makeText(SignInActivity.this, "JSON 构建失败", Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });

        //返回上一Activity
        ImageButton button_back_on_login = findViewById(R.id.button_back_on_sign_in);
        button_back_on_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish(); // 结束当前Activity，返回上一Activity
            }
        });


        //点击图标实现隐藏密码或显示密码功能
        ImageView eye_on_sign_in = findViewById(R.id.eye_on_sign_in);

        eye_on_sign_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentInputType = passwordEditText.getInputType();

                if ((currentInputType & InputType.TYPE_CLASS_TEXT) != 0 &&
                        (currentInputType & InputType.TYPE_TEXT_VARIATION_PASSWORD) != 0) {
                    // 密码当前是隐藏的
                    passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
                    eye_on_sign_in.setImageResource(R.drawable.eye_open); // 显示睁眼图标
                } else {
                    // 密码当前是显示的
                    passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    eye_on_sign_in.setImageResource(R.drawable.eye_close); // 显示闭眼图标
                }
                passwordEditText.setSelection(passwordEditText.getText().length()); // 将光标移动到文本末尾
            }
        });

        //无账号，去注册
        TextView need_an_account_sign_up = findViewById(R.id.need_an_account_sign_up);
        need_an_account_sign_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SignInActivity.this,SignUpActivity.class);
                startActivity(intent);
            }
        });
    }
}